package com.xone.xapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ProductItemActivity extends BasicActivity {
    protected LayoutInflater mInflater;
	@Override
	public String getHeaderTitle() {
		return "产品详情";
	}
	@Override
	public int getContentView() {
		return R.layout.product_item;
	}
	/**
	 * 是否需要检测登录
	 * @return
	 */
	@Override
	public boolean isLoginCheck() {
		return false;
	}
	protected void onCreate(Bundle savedInstanceState) {
		Bundle bundle = this.getIntent().getExtras();
		String id = (null == bundle) ? "" : bundle.getString("id");
		super.onCreate(savedInstanceState);
		if (!ContextUtils.isOnline(this)) {
			return;
		}
		if (null == id) {
			Toast.makeText(this, "缺少请求参数", Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		LinearLayout view = (LinearLayout)findViewById(R.id.product_item_details_zone);
		showProgress();
		this.mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		new InitDataTask(this, view, ContextUtils.getScreenWidth(this)).execute(id);
	}
	
	public class InitDataTask extends AsyncTask<String, Integer, JSONObject> {
		protected Context context;
		protected LinearLayout view;
		protected int imageWidth;
		protected ImageLoader imageLoader = null;
		public InitDataTask(Context context, LinearLayout view, int imageWidth) {
			this.context = context;
			this.imageWidth = imageWidth;
			this.view = view;
			imageLoader = new ImageLoader(context, imageWidth * 2);
		}
		@Override
		protected JSONObject doInBackground(final String... params) {
			if (isCancelled()) {
				return null;
			}
			List<NameValuePair> reqparams = new ArrayList<NameValuePair>();
			reqparams.add(new BasicNameValuePair("product.id", params[0]));
			return HttpUtils.httpGet(Constants.APP_URL + "/product/itemJsonDetails.html", reqparams, 
					new HttpUtils.onGetSuccessListener<JSONObject>() {
						@Override
						public JSONObject onSuccess(int status, String result) {
							if (HttpUtils.SC_OK == status) {
								JSONObject jsonObject = JSONUtils.getJSONObjectFromString(result);
								JSONObject product = JSONUtils.getJSONObjectForKey(jsonObject, "product");
								return product;
							} else {
								Toast.makeText(context, "Status Code:" + status, Toast.LENGTH_SHORT).show();
							}
							return null;
						}
					}, context);
		}
		@Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			if (null == result) {
				return;
			}
				JSONObject product = result;
				JSONObject person = JSONUtils.getJSONObjectForKey(product, "person");
				if (UserInfo.login) {
					view.findViewById(R.id.cellphone_view).setVisibility(View.VISIBLE);
					view.findViewById(R.id.person_cellphone).setVisibility(View.VISIBLE);
					view.findViewById(R.id.contactor_view).setVisibility(View.VISIBLE);
					view.findViewById(R.id.person_contactor).setVisibility(View.VISIBLE);
					view.findViewById(R.id.productPrice_view).setVisibility(View.VISIBLE);
					view.findViewById(R.id.product_productPrice).setVisibility(View.VISIBLE);
					boolean groupSaleType = JSONUtils.getBooleanFromJSONObject(product, "groupSaleType");
					if ((UserInfo.blevelUser || UserInfo.clevelUser) && groupSaleType) {
						view.findViewById(R.id.product_group_type0).setVisibility(View.VISIBLE);
						view.findViewById(R.id.product_group_type1).setVisibility(View.VISIBLE);
						view.findViewById(R.id.product_group_type2).setVisibility(View.VISIBLE);
						view.findViewById(R.id.product_group_type3).setVisibility(View.VISIBLE);
						View toGroup = view.findViewById(R.id.apply_to_group);
						toGroup.setTag(JSONUtils.getStringFromJSONObject(product, "id"));
						toGroup.setOnClickListener(new OnClickListener() {
							@SuppressWarnings("unchecked")
							@Override
							public void onClick(final View v) {
								final EditText groupNumText = (EditText)view.findViewById(R.id.groupNum);
								if (StringUtils.isBlank(groupNumText.getText().toString())) {
									Toast.makeText(getContext(), "请输入组团数量", Toast.LENGTH_SHORT).show();
									return;
								}
								ContextUtils.confirm(getContext(), "确认申请组团？", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										showProgress();
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										params.add(new BasicNameValuePair("productGroup.productId", (String)v.getTag()));
										params.add(new BasicNameValuePair("productGroup.groupNum", groupNumText.getText().toString()));
										new AbstractPostDataTask(getContext()) {
											@Override
											public String getPostUrl() {
												return "/product/doGroupsJson.html";
											}
											@Override
											public void postFinish(JSONObject result) {
												hideProgress();
												if (null != result) {
													v.setEnabled(false);
													Toast.makeText(getContext(), "操作成功", Toast.LENGTH_SHORT).show();
												} else {
													Toast.makeText(getContext(), "操作失败，请联系客服", Toast.LENGTH_SHORT).show();
												}
											}
										}.execute(params);
									}
								});
							}
						});
					}
				}
				int childCount = view.getChildCount();
				for (int i = 0 ; i < childCount; i++) {
					View v = view.getChildAt(i);
					String tag = (String)v.getTag();
					if (v instanceof LinearLayout && ("product".equals(tag) || "person".equals(tag))) {
						String key = context.getResources().getResourceEntryName(v.getId());
						if (null == key) {
							continue;
						}
						String value = null;
						if ("product".equals(tag)) {
							key = key.replaceFirst("product_", "");
							if (!product.isNull(key)) {
								value = JSONUtils.getStringFromJSONObject(product, key);
							}
						} else if ("person".equals(tag)) {
							key = key.replaceFirst("person_", "");
							if (!person.isNull(key)) {
								value = JSONUtils.getStringFromJSONObject(person, key);
							}
						}
						if (null != value) {
							TextView tv = (TextView)view.findViewById(context.getResources().getIdentifier(key, "id", context.getPackageName()));
							if (null != tv) {
								tv.setText(value);
							}
						}
					}
				}
				JSONArray ids = JSONUtils.getJSONArrayForKey(product, "ids");
				if (null != ids && ids.length() > 0) {
					for (int i = 0; i < ids.length(); i++) {
						View mImageView = mInflater.inflate(R.layout.product_show_image, null);
						ImageView imageView = (ImageView)mImageView.findViewById(R.id.product_image_0);
						String imageId = null;
						imageId = JSONUtils.getStringFromJSONArray(ids, i);
						imageLoader.displayImage(Constants.APP_URL + "/assistant/image.html?id=" + imageId, imageView);
						imageView.getLayoutParams().height = imageWidth;
						view.addView(mImageView, childCount + i);
					}
				}
				view.setVisibility(View.VISIBLE);
				hideProgress();
		}
	}
}
